package top.codedance.iotp.registy.net.handle.action;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.entity.ServerMeta;
import top.codedance.iotp.registy.RegistryApplication;
import top.codedance.iotp.registy.net.handle.AdapterController;
import org.apache.log4j.Logger;

import java.util.Date;
import java.util.Map;
import java.util.Set;

public class SyncDataController extends AdapterController {
    private static Logger logger = RegistryApplication.getLogger(SyncDataController.class);

    @Override
    public String doSubHandler(JSONObject body) {
        if(!RegistryApplication.isElectioning) {
            synchronized (RegistryApplication.class) {
                JSONObject servers = body.getJSONObject("servers");
                RegistryApplication.servers.clear();
                Set<Map.Entry<String, Object>> entries = servers.entrySet();
                for (Map.Entry<String, Object> item : entries) {
                    RegistryApplication.addServer(item.getKey(), ServerMeta.parse((String) item.getValue()));
                }
                JSONObject clients = body.getJSONObject("clients");
                RegistryApplication.clients.clear();
                Set<Map.Entry<String, Object>> entries1 = clients.entrySet();
                for (Map.Entry<String, Object> item : entries1) {
                    RegistryApplication.addClient(item.getKey(), (String) item.getValue());
                }
                Date d = new Date();
                RegistryApplication.syncLastTimestamp = d.getTime();
                logger.debug("接到主节点同步数据");
            }
        }
        return okResponse("SUCCESS");
    }
}
